/**
 * 文件：activity_control_single_select.java
 * 包名：com.ronri.ams.sample;   --- 正式发布时需要修正
 * 说明：选择组件
 * 作者：MS During
 * 日期：2017/5/10
 * 历史：
 */
package com.ronri.ams.sample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class activity_control_single_select extends abstract_activity {

    private Context mContext = null;

    // 列表控件
    private ListView mListView = null;

    // 查询输入框
    private EditText mFindKeys = null;

    // 执行查询按钮
    private TextView mbtnSearch = null;

    // 上一页
    private TextView mbtnPrev = null;

    // 下一页
    private TextView mbtnNext = null;

    // 数据源
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();

    // 远程服务器地址
    private String mRemoteAddress = null;

    // 当前页面编号
    private int mPageIndex = 0;

    // 总页数
    private int mPages = 10;

    // 分页行数
    private int mPageCount = 0;

    // 远程数据
    private RemoteDataService mRemoteDB = new RemoteDataService();

    // 关键字名
    private String mKeyName = "key";

    // 获取标题名称
    private String mKeyTitleName = "";

    // 选择模式
    private int mSelectMode = ListView.CHOICE_MODE_SINGLE;

    private String mJson = null;

    // 选择的行信息
    private List<Integer> mSelectItems = new ArrayList<Integer>();

    /***
     * 设置参数
     * @param szRemoteAddress
     * @param szFindKey
     * @param szKeyTitleName
     */
    protected void setParamets(String szRemoteAddress, String szFindKey, String szKeyTitleName)
    {
        mKeyName = szFindKey;
        mRemoteAddress = szRemoteAddress;
        mKeyTitleName =  szKeyTitleName;
    }

    /***
     * 创建内容
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.control_list_select);
        Log.i("aaa","activity_control_single_select");
        mContext = this;

        Bundle bundle = getIntent().getExtras();

        String szTitle = bundle.getString("title");
        String szvTitle = bundle.getString("vtitle");
        mJson = bundle.getString("data");

        // 设置选择模式
        mSelectMode = bundle.getInt("selectMode");

        // 显示标题与右边功能
        setTitle(szTitle, szvTitle);

        // 初始化内容
        init();

        // 获取远程地址信息
        // mRemoteAddress = bundle.getString("remoteAddress");
        mKeyName = bundle.getString("filterKeyName");
        mKeyTitleName = bundle.getString("viewTitleName");

        mListView = (ListView) findViewById(R.id.lvDataItem);
        mFindKeys = (EditText) findViewById(R.id.edtFilterLinkMan);
        mbtnSearch = (TextView) findViewById(R.id.btn_search);
        mbtnPrev = (TextView) findViewById(R.id.pageLeft);
        mbtnNext = (TextView) findViewById(R.id.pageRight);

        /***
         * 按钮查询
         */
        mbtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 刷新第一页
                RefreshPageInfo(1);
            }
        });

        /***
         * 按钮上一页
         */
        mbtnPrev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPageIndex == 1) {
                    Toast.makeText(activity_control_single_select.this,"已是第一页", Toast.LENGTH_SHORT).show();
                }else {
                    // 刷新上一页
                    RefreshPageInfo(mPageIndex - 1);
                }
            }
        });

        /****
         * 按钮下一页
         */
        mbtnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPageIndex == mPageCount) {
                    Toast.makeText(activity_control_single_select.this,"没有更多数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 刷新第一页
                RefreshPageInfo(mPageIndex + 1);
            }
        });

        // 刷新第一页
        RefreshPageInfo(1);
    }

    @Override
    public boolean CancelReturn() {
        setResult(RESULT_CANCELED);
        return super.CancelReturn();
    }

    /***
     * 数据提交
     *
     * @return
     */
    @Override
    public boolean SureReturn() {

        String szSplit = "";
        String szResult = "";

        szResult = "";
        for(Integer iTem : mSelectItems){
            Map<String, Object> map = mItems.get(iTem);
            String szJson = (String)map.get("selectValue");
            szResult = szResult + szSplit + szJson;
            szSplit = ",";
        }

        if (szResult != "") {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("returnValue", "[" + szResult + "]");

            intent.putExtras(bundle);

            setResult(RESULT_OK, intent);
        } else {
            setResult(RESULT_CANCELED);
        }

        return super.SureReturn();
    }

    /****
     * 刷新指定页面信息
     *
     * @param nPageIndex
     */
    private void RefreshPageInfo(int nPageIndex) {
        if (mJson == null) {
            getPageData(nPageIndex);
        }else{
            LoadData(mJson);
        }
    }

    /***
     * 获取指定页面数据
     *
     * @param nPageIndex
     * @return
     */
    private int getPageData(int nPageIndex) {

        String szKeys = "";

        if (mFindKeys != null) {
            szKeys = mFindKeys.getText().toString();
        }

        /**组合参数*/
        Map<String, Object> iTem = new HashMap<String, Object>();
        iTem.put(mKeyName, szKeys);

        // 设置参数
        String szParamets = MergeRemoteParamerts(nPageIndex, mPages, iTem);

        // 获取远程数据
        mRemoteDB.getRemoteData(mRemoteAddress, szParamets, "GET", new RemoteDataService.OnRemoteDataEvent() {
            /***
             * 返回结果
             * @param szString
             */
            @Override
            public void OnResultEvent(String szString) {
                try {
                    // 转换成JSON处理
                    JSONObject json = JSON.parseObject(szString);

                    if (json.containsKey("code")) {
                        int nCode = json.getInteger("code");
                        if (nCode == 0) {
                            JSONObject data = json.getJSONObject("data");
                            JSONArray rows = data.getJSONArray("rows");
                            mPageIndex = data.getInteger("page");

                            // 设置总数
                            if (data.containsKey("total")) {
                                mPageCount = data.getInteger("total");
                            }

                            if(rows.size() >= 0 )
                                mItems.clear();

                            for (int i = 0; i < rows.size(); i++) {
                                JSONObject iTem = rows.getJSONObject(i);

                                if (mKeyTitleName != "") {
                                    if (iTem.containsKey(mKeyTitleName)) {
                                        // 获取Title值
                                        String szTitle = iTem.getString(mKeyTitleName);

                                        // 转换成JSON数据
                                        String szJsonString = iTem.toJSONString();

                                        Map<String, Object> iTemData = new HashMap<String, Object>();

                                        iTemData.put("listTitle", szTitle);
                                        iTemData.put("selectValue", szJsonString);

                                        mItems.add(iTemData);
                                    }
                                }
                            }
                        }else{
                            mPageIndex = 1;
                            mPageCount = 0;
                            mItems.clear();
                        }
                    }else{
                        mPageIndex = 1;
                        mPageCount = 0;
                        mItems.clear();
                    }

                    // 不管接收失败，还是接收成功，刷新数据
                    RefreshData();

                } catch (JSONException ex) {

                }
            }

            /***
             * 进度展示
             * @param nStatus
             */
            @Override
            public void OnRuningState(int nStatus) {
                if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                    WaitDialog.ShowDialog(mContext, "请稍后...");
                } else {
                    WaitDialog.HideDialog();
                }
            }

            /***
             * 回调获取参数
             * @return
             */
            @Override
            public String OnGetCustomParam() {
                return null;
            }
        });

        return -1;
    }

    /***
     * 刷新数据
     */
    public void RefreshData()
    {
        // 刷新数据
        if (mListView != null) {
            ChoiceView adapter = new ChoiceView(activity_control_single_select.this, mItems);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    //获取条目
                    CheckableFrameLayout linearLayout = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
                    if (linearLayout.isChecked()) {
                        if(!mSelectItems.contains(i)){
                            mSelectItems.add(i);
                        }
                    } else {
                        if (mSelectItems.contains(i)){
                            for(int pos=0;pos<mSelectItems.size();pos++){
                              if(mSelectItems.get(pos)==i){
                                  mSelectItems.remove(pos);
                              }
                            }
                        }
                    }
                }
            });

            // 选择模式
            mListView.setChoiceMode(mSelectMode);
            mListView.setAdapter(adapter);
        }
    }

    /***
     * 装载数据
     * @param szJson
     * @return
     */
    public int LoadData(String szJson)
    {
        if (szJson == null)
            return -1;

        JSONArray rows = JSONArray.parseArray(szJson);

        for (int i = 0; i < rows.size(); i++) {
            JSONObject iTem = rows.getJSONObject(i);

            if (mKeyTitleName != "") {
                if (iTem.containsKey(mKeyTitleName)) {
                    // 获取Title值
                    String szTitle = iTem.getString(mKeyTitleName);

                    // 转换成JSON数据
                    String szJsonString = iTem.toJSONString();

                    Map<String, Object> iTemData = new HashMap<String, Object>();

                    iTemData.put("listTitle", szTitle);
                    iTemData.put("selectValue", szJsonString);

                    mItems.add(iTemData);
                }
            }
        }

        // 刷新数据
        if (mListView != null) {
            ChoiceView adapter = new ChoiceView(activity_control_single_select.this, mItems);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    //获取条目
                    CheckableFrameLayout linearLayout = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
                    if (linearLayout.isChecked()) {
                        if(!mSelectItems.contains(i)){
                            mSelectItems.add(i);
                        }
                    } else {
                        if (mSelectItems.contains(i)){
                            for(int pos=0;pos<mSelectItems.size();pos++){
                                if(mSelectItems.get(pos)==i){
                                    mSelectItems.remove(pos);
                                }
                            }
                        }
                    }
                }
            });

            // 选择模式
            mListView.setChoiceMode(mSelectMode);
            mListView.setAdapter(adapter);
        }

        return  -1;
    }


}
